﻿package com.alstudio.module.sns.sina;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.module.sns.base.SnsConfig;
import com.alstudio.utils.formater.numeric.ALNumericUtils;
import com.alstudio.utils.log.ALLog;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuth;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.auth.sso.SsoHandler;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.exception.WeiboHttpException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.legacy.AccountAPI;
import com.sina.weibo.sdk.openapi.legacy.FriendshipsAPI;
import com.sina.weibo.sdk.openapi.legacy.StatusesAPI;

public class SinaWeibo {
	private static final String TAG = "SinaWeibo";

	private String mAppKey = "";
	private String mCallbackUrl = "";
	private WeiboAuth weibo = null;
	private StatusesAPI mStatusesAPI;
	private FriendshipsAPI mFriendshipAPI;
	private Oauth2AccessToken mAccessToken;
	private String mUid = "";
	private String mScreenName = "";
	private SsoHandler mSsoHandler;

	public SinaWeibo(Activity activity, String appKey, String callbackUrl) {
		if (TextUtils.isEmpty(appKey))
			throw new IllegalArgumentException(
					"You must specify your app key when instantiating a SinaWeibo object.");

		mAppKey = appKey;
		mCallbackUrl = callbackUrl;
		weibo = new WeiboAuth(activity, mAppKey, mCallbackUrl, SnsConfig.SINA_SCOPE);
		mAccessToken = AccessTokenKeeper.readAccessToken(activity);
		mSsoHandler = new SsoHandler(activity, weibo);
		mStatusesAPI = new StatusesAPI(
				AccessTokenKeeper.readAccessToken(activity));
		mFriendshipAPI = new FriendshipsAPI(AccessTokenKeeper.readAccessToken(activity));
		mUid = AccessTokenKeeper.readUid(activity);
		mScreenName = AccessTokenKeeper.readName(activity);
	}

	public Oauth2AccessToken getAccessToken() {
		return this.mAccessToken;
	}

	public void setAccessToken(Oauth2AccessToken token) {
		if (token == null)
			throw new IllegalArgumentException();

		this.mAccessToken = token;
	}

	public String getUid() {
		return this.mUid;
	}

	public boolean isSessionValid() {
		if(mAccessToken != null){
			return mAccessToken.isSessionValid();
		}
		return false;
	}

	public void resetToken() {
		mAccessToken = null;
	}

	public void authorize(Activity activity, OnAuthEventListener listener) {
		mSsoHandler.authorize(new SinaWeiboAuthListener(activity, listener));
	}

	private String getSinaUid(String response) throws WeiboException,
			JSONException {
		String result = "";

		JSONObject jsonObj = new JSONObject(response);
		result = jsonObj.getString("uid");
		return result;
	}

	public UserInfo getUserInfo(String response) throws WeiboException,
			JSONException {

		UserInfo user = new UserInfo();
		JSONObject jsonObj = new JSONObject(response);
		user.setId(jsonObj.getString("id"));
		user.setScreenName(jsonObj.getString("screen_name"));
		user.setName(jsonObj.getString("name"));
		user.setGender("m".equals(jsonObj.getString("gender")) ? "male"
				: "female");

		return user;
	}

	public void authorizeCallBack(int requestCode, int resultCode, Intent data) {
		if (mSsoHandler != null) {
			mSsoHandler.authorizeCallBack(requestCode, resultCode, data);
		}
	}

	public void getUserInfoAsyn(Callback callback, final String response) {
		final Callback const_callback = callback;
		new Thread() {
			@Override
			public void run() {
				UserInfo user = null;
				try {
					user = getUserInfo(response);
				} catch (WeiboHttpException e) {
					e.printStackTrace();

					if (const_callback != null)
						const_callback.onError(e.getStatusCode(),
								e.getMessage());

					return;
				} catch (JSONException e) {
					e.printStackTrace();

					if (const_callback != null)
						const_callback.onError(0, e.getMessage());

					return;
				}

				if (const_callback != null)
					const_callback.onSuccess(user);
			}
		}.start();
	}

	public void createFriendship(long response,RequestListener listener) throws WeiboException {
		
		if(mFriendshipAPI == null){
			ALLog.e("我回去了");
			return;
		}
		mFriendshipAPI.create(response, "", listener);

	}

	

	public void updateStatusWithImage(String content, String imageData,
			RequestListener listener) throws WeiboException {

		mStatusesAPI.upload(content, imageData, null, null, listener);

	}

	public void updateStatusWithImageUrl(String content, String imageUrl,
			RequestListener listener) throws WeiboException {
		mStatusesAPI.uploadUrlText(content, imageUrl, null, null,null, listener);
	}

	/**
	 * 获取用户的关注列表
	 * @param listener
	 */
	public void getFriends(RequestListener listener) {
		//最多只取200个
		mFriendshipAPI.friends(ALNumericUtils.parseLong(mUid, 0), 200, 0, true, listener);
	}
	
	/**
	 * 关注对面
	 * @param uid
	 * @param screen_name
	 * @param listener
	 */
	public void keepImeach(Long uid,String screen_name,RequestListener listener){
		mFriendshipAPI.create(uid,screen_name, listener);
	}

	private RequestListener requestListener = new RequestListener() {

		@Override
		public void onIOException(IOException e) {
			e.printStackTrace();
		}

		@Override
		public void onError(WeiboException e) {
			e.printStackTrace();
		}

		@Override
		public void onComplete(String response) {
			try {
				ALLog.d( "获取用户ID");
				mUid = getSinaUid(response);
//				mScreenName = getUserInfo(response).getScreenName();
				AccessTokenKeeper.setName(ALLocalEnv.getLocalEnv().getApplicationContext(), mScreenName);
				AccessTokenKeeper.setUid(ALLocalEnv.getLocalEnv().getApplicationContext(), mUid);
				if (mListener != null) {
					mListener.onAuthSuccess();
				}
			} catch (WeiboHttpException  e) {
				e.printStackTrace();

				if (e.getStatusCode() == 21327) {
					ALLog.d( "过期啦。");

					resetToken();

					return;
				}

				return;
			} catch (JSONException e) {
				e.printStackTrace();

				return;
			}
		}

		@Override
		public void onComplete4binary(ByteArrayOutputStream arg0) {
			// TODO Auto-generated method stub
			
		}
	};

	private OnAuthEventListener mListener;
	private AccountAPI mAccountAPI;

	private class SinaWeiboAuthListener implements WeiboAuthListener {

		protected OnAuthEventListener listener = null;
		protected Activity activity = null;

		public SinaWeiboAuthListener(Activity activity,
				OnAuthEventListener listener) {
			this.activity = activity;
			this.listener = listener;
			mListener = listener;
		}

		@Override
		public void onComplete(Bundle values) {
			String token = values.getString("access_token");
			String expires_in = values.getString("expires_in");
			mAccessToken = new Oauth2AccessToken(token, expires_in);
			AccessTokenKeeper.keepAccessToken(activity, mAccessToken);
//			weibo.accessToken = mAccessToken;
			ALLog.d(
					"认证成功: \r\n access_token: "
							+ token
							+ "\r\n"
							+ "expires_in: "
							+ expires_in
							+ "\r\n有效期："
							+ new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")
									.format(new java.util.Date(mAccessToken
											.getExpiresTime())));

			mAccountAPI = new AccountAPI(mAccessToken);
			mStatusesAPI = new StatusesAPI(mAccessToken);
			mAccountAPI.getUid(requestListener);
			mFriendshipAPI = new FriendshipsAPI(mAccessToken);
		}

		@Override
		public void onCancel() {
			ALLog.e( "auth cancel");

			if (listener != null)
				listener.onCancel();
		}

		@Override
		public void onWeiboException(WeiboException e) {
			ALLog.e( e.getMessage());

			if (listener != null)
				listener.onAuthFailed(e.getMessage());
		}
	};

	public interface OnAuthEventListener {
		// 授权验证成功
		void onAuthSuccess();

		// 取消
		void onCancel();

		// 授权验证失败
		void onAuthFailed(String msg);

	}

	public interface Callback {
		void onSuccess(Object obj);

		void onError(int ret, String msg);
	}
}
